from rest_framework import serializers

from courses.models import Course, Teacher, CourseChapter, CourseLesson


class TeacherSerializer(serializers.ModelSerializer):
    class Meta:
        model = Teacher
        fields = ['id', 'name', 'title']


class CourseSerializer(serializers.ModelSerializer):
    # 付费类型的文本,这字段在模型中不存在,它来自与一个方法
    course_type_text = serializers.SerializerMethodField()

    teacher = TeacherSerializer(read_only=True)

    class Meta:
        model = Course
        fields = ['id', 'name', 'brief', 'course_img', 'students'
            , 'lessons', 'original_price', 'price', 'course_type', 'course_type_text', "teacher"]

    def get_course_type_text(self, obj):
        return obj.get_course_type_display()


class TeacherDetailSerializer(serializers.ModelSerializer):
    """
    课程讲师详情序列化器
    """

    class Meta:
        model = Teacher
        fields = '__all__'


class LessonSerializer(serializers.ModelSerializer):
    """
    课时序列化器
    """

    class Meta:
        model = CourseLesson
        fields = '__all__'


class ChapterSerializer(serializers.ModelSerializer):
    """
    章节序列化器
    """

    lessons = LessonSerializer(many=True, read_only=True)

    class Meta:
        model = CourseChapter
        fields = '__all__'


class CourseDetailSerializer(serializers.ModelSerializer):
    """
    课程详情序列化器
    """
    teacher = TeacherDetailSerializer(read_only=True)
    chapters = ChapterSerializer(read_only=True, many=True)

    class Meta:
        model = Course
        fields = '__all__'


class CourseLessonSerializer(serializers.ModelSerializer):
    """
    课时
    """

    lesson_type_text = serializers.CharField(source='get_lesson_type_display', read_only=True)

    class Meta:
        model = CourseLesson
        fields = ['id', 'title', 'orders', 'lesson_type', 'lesson_type_text', 'link', 'duration', 'pub_date',
                  'is_free_trail']


class CourseChapterSerializer(serializers.ModelSerializer):
    """
    课程章节
    """
    lessons = CourseLessonSerializer(many=True, read_only=True)

    class Meta:
        model = CourseChapter
        fields = ['id', 'title', 'number', 'summary', 'pub_date', 'lessons']
